package com.RLFZ.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.RLFZ.entity.Menu;
import com.RLFZ.entity.Role;
import com.RLFZ.service.MenuService;
import com.RLFZ.service.RoleService;
import com.RLFZ.service.UserService;
import com.RLFZ.utils.TreeNode;
import com.RLFZ.vo.DataView;
import com.RLFZ.vo.RoleVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 86166
 */
@Controller
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private RoleService roleService;
    // 初始化下拉菜单权限
    @Autowired
    private MenuService menuService;

    @Autowired
    private UserService userService;

    @RequestMapping("/toRole")
    public String toRole(){
        return "role/role";
    }
    /**
     * 查询所有角色带有分页，带有条件查询
     */
    @RequestMapping("/loadAllRole")
    @ResponseBody
    public DataView loadAllRole(RoleVo roleVo){
        IPage<Role> page=new Page<>(roleVo.getPage(),roleVo.getLimit());
        QueryWrapper<Role> queryWrapper=new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNoneBlank(roleVo.getName()),"name",roleVo.getName());
        queryWrapper.like(StringUtils.isNoneBlank(roleVo.getRemark()),"remark",roleVo.getRemark());
        roleService.page(page,queryWrapper);
        return new DataView(page.getTotal(),page.getRecords());
    }

    /**
     * 新增角色
     * @param role
     * @return
     */
    @RequestMapping("/addRole")
    @ResponseBody
    public DataView addRole(Role role){
        DataView dataView=new DataView();
        boolean save = roleService.save(role);
        if (!save){
            dataView.setCode(100);
            dataView.setMsg("角色插入失败");
        }
        dataView.setMsg("角色插入成功");
        dataView.setCode(200);
        return dataView;
    }

    /**
     * 修改菜单
     */
    @RequestMapping("/updateRole")
    @ResponseBody
    public DataView updateRole(Role role){
        roleService.updateById(role);
        DataView dataView=new DataView();
        dataView.setCode(200);
        dataView.setMsg("更新角色成功！");
        return dataView;
    }
    /**
     * 删除角色
     */
//    @RequestMapping("/deleteRole")
//    @ResponseBody
//    public DataView deleteMenu(Role role){
//        roleService.removeById(role.getId());
//        DataView dataView=new DataView();
//        dataView.setCode(200);
//        dataView.setMsg("删角色成功！");
//        return dataView;
//    }
    @RequestMapping("/initPermissionByRoleId")
    @ResponseBody
    public DataView initPermissionByRoleId(Integer roleId){
        //查询所有菜单和权限
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        List<Menu> allPermissions = menuService.list();
        //1.首先根据角色id查询出当前角色所拥有的所有菜单的ID和权限的ID
        List<Integer> currentRolePermissions = roleService.queryRolePermissionIdsByRid(roleId);
        //2.根据查询出来的菜单ID和权限ID，再查询出菜单的数据和权限的数据
        List<Menu> currentPermissions = null;

        //如果根据角色id查询出来了菜单ID或权限ID，就去查询
        if (currentRolePermissions.size()>0){
            queryWrapper.in("id",currentRolePermissions);
            currentPermissions = menuService.list(queryWrapper);
        }else {
            currentPermissions = new ArrayList<>();
        }
        //3.构造List<TreeNode>
        List<TreeNode> nodes = new ArrayList<>();
        for (Menu allPermission : allPermissions) {
            String checkArr = "0";
            for (Menu currentPermission : currentPermissions) {
                if (allPermission.getId().equals(currentPermission.getId())){
                    checkArr = "1";
                    break;
                }
            }
            Boolean spread = (allPermission.getOpen()==null||allPermission.getOpen()==1)?true:false;
            nodes.add(new TreeNode(allPermission.getId(),allPermission.getPid(),allPermission.getTitle(),spread,checkArr));
        }
        return new DataView(nodes);
    }

    /**
     * 点击保存时把数据保存到数据库
     */
    @RequestMapping("/saveRolePermission")
    @ResponseBody
    public DataView saveRolePermission(Integer rid,Integer[] mids){
        // 1.删除之前权限根据id
        roleService.deleteRoleByRid(rid);
        //保存权限
        if (mids!=null && mids.length>0){
            for (Integer mid: mids){
                roleService.saveRoleMenu(rid,mid);
            }
        }
        DataView dataView=new DataView();
        dataView.setCode(200);
        dataView.setMsg("菜单权限分配成功");
        return dataView;
    }

    /**
     * 保存用户角色之间的关系 1:m
     * 先删除后保存
     */
    @RequestMapping("/saveUserRole")
    @ResponseBody
    public DataView saveUserRole(Integer uid, Integer[] ids){
        userService.saveUserRole(uid,ids);
        DataView dataView=new DataView();
        dataView.setCode(200);
        dataView.setMsg("角色分配成功");
        return dataView;
    }
}
